package markan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class PostSubmit {

	public void sendData(String sendUrl, String message) {
		
		System.out.println(sendUrl);
		System.out.println(message);

		URL url = null;
		HttpURLConnection http = null;
		OutputStreamWriter outStream = null;
		PrintWriter writer = null;
		InputStreamReader tmp = null;
		BufferedReader reader = null;
		try {
			url = new URL(sendUrl);
			http = (HttpURLConnection) url.openConnection();

			http.setDefaultUseCaches(false);
			http.setDoInput(true); // 서버에서 읽기 모드 지정
			http.setDoOutput(true); // 서버로 쓰기 모드 지정
			http.setRequestMethod("POST"); // 전송 방식은 POST
			http.setRequestProperty("content-type", "application/x-www-form-urlencoded");

			// --------------------------
			// 서버로 값 전송
			// --------------------------
			outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
			writer = new PrintWriter(outStream);
			writer.write(message);
			writer.flush();

			// 서버에서 전송받기
			tmp = new InputStreamReader(http.getInputStream(), "UTF-8");
			reader = new BufferedReader(tmp);
			StringBuilder builder = new StringBuilder();
			String str;
			while ((str = reader.readLine()) != null) {
				builder.append(str + "\n");
			}
			String myResult = builder.toString();
			System.out.println(myResult);
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (tmp != null) {
				try {
					tmp.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (writer != null)
				writer.close();
			if (outStream != null) {
				try {
					outStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (http != null)
				http.disconnect();

		}
	}
}